export function timeFix() {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? "早上好" : hour <= 11 ? "上午好" : hour <= 13 ? "中午好" : hour < 20 ? "下午好" : "晚上好"
}

export function welcome() {
  const arr = ["休息一会儿吧", "准备吃什么呢?", "要不要打一把 DOTA", "我猜你可能累了"]
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent() {
  const event = document.createEvent("HTMLEvents")
  event.initEvent("resize", true, true)
  event.eventType = "message"
  window.dispatchEvent(event)
}

export function handleScrollHeader(callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function() {
  }
  window.addEventListener(
    "scroll",
    event => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = "up"
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? "down" : "up"
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

export const setDocumentTitle = function(title) {
  document.title = title
  const ua = navigator.userAgent
  // eslint-disable-next-line
  const regex = /\bMicroMessenger\/([\d\.]+)/
  if (regex.test(ua) && /ip(hone|od|ad)/i.test(ua)) {
    const i = document.createElement("iframe")
    i.src = "/favicon.ico"
    i.style.display = "none"
    i.onload = function() {
      setTimeout(function() {
        i.remove()
      }, 9)
    }
    document.body.appendChild(i)
  }
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate(id = "", timeout = 1500) {
  if (id === "") {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}

export const listToTree2 = (array, opt) => {
  const obj = {
    primaryKey: opt.primaryKey || "key",
    parentKey: opt.parentKey || "parentId",
    titleKey: opt.titleKey || "title",
    startPid: opt.startPid || "0",
    currentDept: opt.currentDept || 0,
    maxDept: opt.maxDept || 100,
    childKey: opt.childKey || "children"
  }
  return toTree(array, obj.startPid, obj.currentDept, obj)
}
/**
 *  实际的递归函数，将会变化的参数抽取出来
 * @param list
 * @param startPid
 * @param currentDept
 * @param opt
 * @returns {Array}
 */
export const toTree = (array, startPid, currentDept, opt) => {
  if (opt.maxDept < currentDept) {
    return []
  }
  let child = []
  if (array && array.length > 0) {
    child = array.map(item => {
      // 筛查符合条件的数据（主键 = startPid）
      if (typeof item[opt.parentKey] !== "undefined" && item[opt.parentKey] === startPid) {
        // 满足条件则递归
        const nextChild = toTree(array, item[opt.primaryKey], currentDept + 1, opt)
        // 节点信息保存
        if (nextChild.length > 0) {
          item["isLeaf"] = false
          item[opt.childKey] = nextChild
        } else {
          item["isLeaf"] = true
        }
        item["title"] = item[opt.titleKey]
        item["label"] = item[opt.titleKey]
        item["key"] = item[opt.primaryKey]
        item["value"] = item[opt.primaryKey]
        return item
      }
    }).filter(item => {
      return item !== undefined
    })
  }
  return child
}

/**
 * 生成uuid
 */
export function uuid() {
  let s = []
  let hexDigits = "0123456789abcdef"
  for (let i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = "4" // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-"
  return s.join("")
}

/**
 * 动态给对象赋值
 * @param optionModel 赋值对象
 * @param prop 赋值属性 例如a.b.c
 * @param value 值
 */
export function setValueByPath(optionModel, prop, value) {
  let propArray = prop.split(".")
  if (propArray.length > 0) {
    let tempObj = optionModel
    propArray.forEach((item, index) => {
      if (index == propArray.length - 1) {
        tempObj[item] = value
        return
      }
      let obj = tempObj[item]
      if (!obj) {
        tempObj[item] = {}
      }
      tempObj = tempObj[item]
    })
  }

}

/**
 * eval("optionModel.value." + prop + "=" + e.target.value)
 * 根据属性路径获取属性值
 * @param obj
 * @param path a.b.c
 */
export function getPropByPath(obj, path) {
  let tempObj = obj
  path = path.replace(/\[(\w+)\]/g, ".$1")
  path = path.replace(/^\./, "")

  let keyArr = path.split(".")
  let i = 0

  for (let len = keyArr.length; i < len - 1; ++i) {
    let key = keyArr[i]
    if (key in tempObj) {
      console.info("tempObj", tempObj)
      tempObj = tempObj[key]
    } else {
      throw new Error("[iView warn]: please transfer a valid prop path to form item!")
    }
  }
  return {
    o: tempObj,
    k: keyArr[i],
    v: tempObj[keyArr[i]]
  }
}

/**
 *根据属性路径获取属性值
 * @param {*} object { aaa: { bbb: { ccc: 123 } } }
 * @param {*} prop "aaa.bbb.ccc"
 */
export function getValueByPath(object, prop) {
  prop = prop || ""
  const paths = prop.split(".")
  let current = object
  let result = null
  for (let i = 0, j = paths.length; i < j; i++) {
    const path = paths[i]
    if (!current) break

    if (i === j - 1) {
      result = current[path]
      break
    }
    current = current[path]
  }
  return result
}

export function conver(limit) {
  let size = ""
  if (limit < 0.1 * 1024) { //如果小于0.1KB转化成B
    size = limit.toFixed(2) + "B"
  } else if (limit < 0.1 * 1024 * 1024) {//如果小于0.1MB转化成KB
    size = (limit / 1024).toFixed(2) + "KB"
  } else if (limit < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB
    size = (limit / (1024 * 1024)).toFixed(2) + "MB"
  } else { //其他转化成GB
    size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB"
  }

  let sizestr = size + ""
  let len = sizestr.indexOf("\.")
  let dec = sizestr.substr(len + 1, 2)
  if (dec == "00") {//当小数点后为00时 去掉小数部分
    return sizestr.substring(0, len) + sizestr.substr(len + 3, 2)
  }
  return sizestr
}
